package com.zzyl.base;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import io.swagger.annotations.ApiModel;
import lombok.*;

import java.io.Serializable;
import java.util.List;

import static cn.hutool.core.convert.Convert.toLong;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@ApiModel(value = "分页结果包装", description = "分页结果包装")
public class PageBean<T> implements Serializable {
	//总条目数
	private Long total = 0L;
	//页尺寸
	private Integer pageSize = 0;
	//总页数
	private Long pages = 0L;
	//页码
	private Integer page = 0;
	//数据列表
	private List<T> records = List.of();
	
	/**
	 * 返回一个分页对象实例
	 * @param <T>
	 * @return
	 */
	public static <T> PageBean<T> empty() {
		return PageBean.<T>builder().build();
	}
	
	/**
	 * 将Page转换为PageBean
	 * @param page
	 * @param <T>
	 * @return
	 */
	public static <T> PageBean<T> of(Page<T> page) {
		if (page == null) {
			return empty();
		}
		if (CollUtil.isEmpty(page.getResult())) {
			return empty();
		}
		return PageBean.<T>builder()
				.page(page.getPageNum())
				.pageSize(page.getPageSize())
				.pages(toLong(page.getPages()))
				.total(page.getTotal())
				.records(page.getResult())
				.build();
	}
	
	/**
	 * Page数据类型和目标类型不同，这里需要指定
	 * @param page
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> PageBean<T> of(Page<?> page, Class<T> clazz) {
		return PageBean.<T>builder()
				.page(page.getPageNum())
				.pageSize(page.getPageSize())
				.pages(toLong(page.getPages()))
				.total(page.getTotal())
				.records(BeanUtil.copyToList(page.getResult(), clazz))
				.build();
	}
	
	/**
	 * 提供了现有的记录List
	 * @param page
	 * @param list
	 * @param <T>
	 * @return
	 */
	public static <T> PageBean<T> of(Page<?> page, List<T> list) {
		return PageBean.<T>builder()
				.page(page.getPageNum())
				.pageSize(page.getPageSize())
				.pages(toLong(page.getPages()))
				.total(page.getTotal())
				.records(list)
				.build();
	}
}
